package es.mllacer.qqsm.tasks;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;
import es.mllacer.qqsm.R;

public class AddFriendTask extends AsyncTask<Void, Integer, Boolean> {

	private static final String ADD_FRIEND_URI = "http://soletaken.disca.upv.es:8080/CMU/rest/friends";

	private static final int WRONG_PARAMETERS = 0;

	private static final int CORRECT_PARAMETERS = 1;

	private static final int SERVICE_NOT_AVAILABLE = 2;

	private Activity activity = null;

	public AddFriendTask(Activity activity) {
		this.activity = activity;
	}

	@Override
	protected void onPreExecute() {
		// nothing to do
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		TextView nameView = (TextView) activity
				.findViewById(R.id.settings_name);
		TextView friendView = (TextView) activity
				.findViewById(R.id.settings_friend);

		String name = nameView.getText().toString();
		String friend = friendView.getText().toString();

		if (name == null || "".equals(name) || friend == null
				|| "".equals(friend)) {
			publishProgress(WRONG_PARAMETERS);
			return true;
		}

		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);

		HttpClient client = new DefaultHttpClient(httpParams);
		HttpPost request = new HttpPost(ADD_FRIEND_URI);

		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("name", name));
		pairs.add(new BasicNameValuePair("friend_name", friend));

		try {
			request.setEntity(new UrlEncodedFormEntity(pairs));
			client.execute(request);
			publishProgress(CORRECT_PARAMETERS);
		} catch (IOException e) {
			publishProgress(SERVICE_NOT_AVAILABLE);
		}

		return true;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		for (int v : values) {
			if (v == WRONG_PARAMETERS) {
				Toast.makeText(activity.getApplicationContext(),
						R.string.settings_button_friend_wrong_message,
						Toast.LENGTH_SHORT).show();
			} else if (v == CORRECT_PARAMETERS) {
				Toast.makeText(activity.getApplicationContext(),
						R.string.settings_button_friend_correct_message,
						Toast.LENGTH_SHORT).show();
			} else if (v == SERVICE_NOT_AVAILABLE) {
				Toast.makeText(activity.getApplicationContext(),
						R.string.settings_service_not_available,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

}
